package cc.orange.mainView;

import androidx.databinding.DataBindingUtil;
import cc.orange.BuildConfig;
import cc.orange.R;
import cc.orange.base.BaseActivity;
import cc.orange.databinding.ActivitySettingBinding;
import cc.orange.entity.BaseEntity;
import cc.orange.entity.IsLoginsEntity;
import cc.orange.entity.UserInfoEntity;
import cc.orange.http.ApiService;
import cc.orange.utils.HProgressDialogUtils;
import cc.orange.utils.RequestPermissions;
import demo.smart.access.xutlis.util.ZXAppUtil;
import demo.smart.access.xutlis.util.ZXSharedPrefUtil;
import demo.smart.access.xutlis.util.ZXSystemUtil;
import cc.orange.utils.ZXToastUtil;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;

//import com.tendcloud.tenddata.TalkingDataSDK;
import com.xcheng.retrofit.Call;
import com.xcheng.retrofit.DefaultCallback;
import com.xcheng.retrofit.HttpError;
import com.xcheng.retrofit.RetrofitFactory;
import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xupdate._XUpdate;
import com.xuexiang.xupdate.service.OnFileDownloadListener;
import com.xuexiang.xupdate.utils.FileUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

public class SettingActivity extends BaseActivity implements View.OnClickListener{

    private ActivitySettingBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_setting);
        initView();
    }

    private void initView() {
        binding.settingText4.setText("v"+ ZXAppUtil.getAppVersionName());
        binding.settingBack.setOnClickListener(this);
        binding.settingClick1.setOnClickListener(this);
        binding.settingClick2.setOnClickListener(this);
        binding.settingClick3.setOnClickListener(this);
        binding.settingClick4.setOnClickListener(this);
        binding.settingClick5.setOnClickListener(this);
        binding.settingClick6.setOnClickListener(this);
        binding.settingClick7.setOnClickListener(this);

        ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
        boolean putswitch = ss.getBool("putswitch_talk", false);
        binding.mineSwitch.setChecked(putswitch);

        binding.mineSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                ss.putBool("putswitch_talk", binding.mineSwitch.isChecked());
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.setting_back:
                finish();
                break;
            case R.id.setting_click1:
                WebViewActivity.openH5Activity(SettingActivity.this,"用户协议", BuildConfig.WEBS_URL1);
                break;
            case R.id.setting_click2:
                WebViewActivity.openH5Activity(SettingActivity.this,"隐私政策",BuildConfig.WEBS_URL2);
                break;
            case R.id.setting_click3:
//                showDialogs(2);
                Intent intent = new Intent(SettingActivity.this, Conversation4KFActivity.class);
                startActivity(intent);
                break;
            case R.id.setting_click4:
                break;
            case R.id.setting_click5:
                getSuserInfo();
                break;
            case R.id.setting_click6:
                WebViewActivity.openH5Activity(SettingActivity.this,"应用权限说明",BuildConfig.WEBS_URL3);
                break;
            case R.id.setting_click7:
                showDialogs(1);
                break;
        }
    }



    private void getSuserInfo(){

        RetrofitFactory.create(ApiService.class)
                .getSuserInfo(getTokens())
                .enqueue(new DefaultCallback<UserInfoEntity>() {
                    @Override
                    public void onStart(Call<UserInfoEntity> call) {
                        showLoading_base(SettingActivity.this);
                    }

                    @Override
                    public void onError(Call<UserInfoEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<UserInfoEntity> call, UserInfoEntity baseEntity) {
                        cancelLoading();
                        if(baseEntity.getCode() == 0){

                            if(baseEntity.getData().getVersionCode() > ZXSystemUtil.getVersionCode()){
//                                showDialogsUpData("uploa_"+ HOST+"/api/load/download/"+getNems());
                            } else{
                                ZXToastUtil.showToast("当前以是最新版本");
                            }
                        }else{
                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }

    private void showDialogsUpData(String urls){
        AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this);       // 创建对话框构建器
        builder.setTitle("");                                           // 设置对话框的标题
        builder.setMessage("发现新版本！请点击确定下载更新");//设置对话框提示语句
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                getPermissions_storage(urls);
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.create().show();
    }



    private void getPermissions_storage(String url) {
        RequestPermissions.getPermissions_storage(SettingActivity.this, new RequestPermissions.SuccessInterf() {
            @Override
            public void onSuccess() {
                XUpdate.newBuild(SettingActivity.this)
                        .supportBackgroundUpdate(true)
                        .apkCacheDir(FileUtils.getExtDownloadsPath()) //设置下载缓存的根目录
                        .build()
                        .download(url, new OnFileDownloadListener() {   //设置下载的地址和下载的监听
                            @Override
                            public void onStart() {
                                HProgressDialogUtils.showHorizontalProgressDialog(SettingActivity.this, "下载进度", false);
                            }

                            @Override
                            public void onProgress(float progress, long total) {
                                HProgressDialogUtils.setProgress(Math.round(progress * 100));
                            }

                            @Override
                            public boolean onCompleted(File file) {
                                HProgressDialogUtils.cancel();
                                ZXToastUtil.showToast("apk下载完毕，文件路径：" + file.getPath());
                                _XUpdate.startInstallApk(SettingActivity.this,
                                        FileUtils.getFileByPath(file.getPath())); //填写文件所在的路径
                                return false;
                            }

                            @Override
                            public void onError(Throwable throwable) {
                                HProgressDialogUtils.cancel();
                            }
                        });
            }
        });
    }


    private void showDialogs(int type){
        AlertDialog.Builder builder = new AlertDialog.Builder(SettingActivity.this);       //
        builder.setTitle("");// 设置对话框的标题
        builder.setMessage("确定要注销账号吗？账号注销后，您的所有信息将被清除");

        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteUser();
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.create().show();
    }


    private void deleteUser() {
        RetrofitFactory.create(ApiService.class)
                .deleteUser(getTokens())
                .enqueue(new DefaultCallback<BaseEntity>() {
                    @Override
                    public void onStart(Call<BaseEntity> call) {
                        showLoading_base(SettingActivity.this);
                    }

                    @Override
                    public void onError(Call<BaseEntity> call, HttpError error) {
                        cancelLoading();
                    }

                    @Override
                    public void onSuccess(Call<BaseEntity> call, BaseEntity baseEntity) {
                        cancelLoading();
                        if (baseEntity.getCode() == 0) {
                            ZXSharedPrefUtil ss = new ZXSharedPrefUtil();
                            ss.clear();
                            EventBus.getDefault().post(new IsLoginsEntity(false));
                            ZXToastUtil.showToast("账号注销成功");
                        } else {
//                            ZXToastUtil.showToast(baseEntity.getMsg());
                        }
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
//        TalkingDataSDK.onPageBegin(this, getLocalClassName());
    }

    @Override
    protected void onPause() {
        super.onPause();
//        TalkingDataSDK.onPageEnd(this, getLocalClassName());
    }
}